# -*- encoding:utf-8 -*-
# -*- encoding:gbk -*-

from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
import poplib

hostname = 'pop.qq.com'
user = '908516511@qq.com'
passwd = 'uadlbosxgabrbdeh'


# indent用于缩进显示:
def print_info(msg, indent=0):
    if indent == 0:
        # 邮件的From, To, Subject存在于根对象上:
        for header in ['From', 'To', 'Subject']:
            value = msg.get(header, '')
            if value:
                if header == 'Subject':
                    # 需要解码Subject字符串:
                    value = decode_str(value)
                else:
                    # 需要解码Email地址:
                    hdr, addr = parseaddr(value)
                    name = decode_str(hdr)
                    value = u'%s <%s>' % (name, addr)
            print('%s%s: %s' % ('  ' * indent, header, value))
    if (msg.is_multipart()):
        # 如果邮件对象是一个MIMEMultipart,
        # get_payload()返回list，包含所有的子对象:
        parts = msg.get_payload()
        for n, part in enumerate(parts):
            print('%spart %s' % ('  ' * indent, n))
            print('%s--------------------' % ('  ' * indent))
            # 递归打印每一个子对象:
            print_info(part, indent + 1)
    else:
        # 邮件对象不是一个MIMEMultipart,
        # 就根据content_type判断:
        content_type = msg.get_content_type()
        print(content_type)
        if content_type == 'text/plain' or content_type == 'text/html':
            # 纯文本或HTML内容:
            content = msg.get_payload(decode=True)
            print(content)
            # 要检测文本编码:
            charset = guess_charset(msg)
            if charset:
                content = content.decode(charset)
            print('%sText: %s' % ('  ' * indent, content + '...'))
        else:
            # 不是文本,作为附件处理:
            print('%sAttachment: %s' % ('  ' * indent, content_type))


def decode_str(s):
    value, charset = decode_header(s)[0]
    if charset:
        value = value.decode(charset)
    return value


def guess_charset(msg):
    # 先从msg对象获取编码:
    charset = msg.get_charset()
    if charset is None:
        # 如果获取不到，再从Content-Type字段获取:
        content_type = msg.get('Content-Type', '').lower()
        pos = content_type.find('charset=')
        if pos >= 0:
            charset = content_type[pos + 8:].strip()
    return charset

p = poplib.POP3_SSL(hostname)  # 与SMTP一样，登录gmail需要使用POP3_SSL() 方法，返回class POP3实例

try:
    # 使用POP3.user(), POP3.pass_()方法来登录个人账户
    p.user(user)
    p.pass_(passwd)
except poplib.error_proto:  # 可能出现的异常
    print('login failed')
else:
    response, listings, octets = p.list()
    print(len(listings))
    resp, lines, octets = p.retr(len(listings))
    # lines存储了邮件的原始文本的每一行,
    # 可以获得整个邮件的原始文本:

    msg = Parser().parsestr(str(lines))
    print_info(msg)
    print(msg)

finally:
    print('log out')
    p.quit()


